import json

import pyodbc

from test_api import getdir


class DatabaseManager:
    def __init__(self):
        self.connection = None

    def connect(self):
        self.settings_file = getdir() + 'api/ConfigJson.txt'
        with open(self.settings_file, 'r', encoding='utf-8') as file:
            settings = json.load(file)
        # 构建连接字符串
        connection_string = (
            r'DRIVER={{ODBC Driver 17 for SQL Server}};'
            r'SERVER={dataIp};'  # 使用 settings['dataIp']
            r'DATABASE={database};'
            r'UID={user};'
            r'PWD={password}'
        ).format(dataIp=settings['dataIp'], database=settings['database'], user=settings['user'],
                 password=settings['password'])
        try:
            self.connection = pyodbc.connect(connection_string)
            print("数据库连接成功")
        except pyodbc.Error as e:
            print("数据库连接失败：", e)

    def close(self):
        if self.connection:
            self.connection.close()
            print("数据库连接已关闭")
